﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BISPOS.Repository;
using System.Linq;
namespace BISPOS
{
    public partial class POSForm : DevExpress.XtraEditors.XtraForm
    {

        public Employee employee;
        List<Customer> allCustomers= new List<Customer>();
        public List<Product> allProducts = new List<Product>();

        public Customer customer;
        public PaymentType paymentType;
        public POSGridItem selectedItem;
        public decimal totalPrice;

        CustomerRepository customerRepository = new CustomerRepository();
        ProductRepository productRepository = new ProductRepository();
        InvoiceRepository invoiceRepository = new InvoiceRepository();
        public POSForm(Employee _employee)
        {
            InitializeComponent();
            employee = _employee;
            ResetForm();
        }
        public void UpdateTotalPrice()
        {
            totalPrice = pOSGridItemBindingSource.OfType<POSGridItem>().Sum(x => x.TotalPrice);
            totalPriceTextEdit.Text = totalPrice.ToString("C2");
        }
        public void AddProduct(Product product)
        {
            if (pOSGridItemBindingSource.OfType<POSGridItem>().Any(x => x.ProductId == product.Id))
            {
                POSGridItem existingItem = pOSGridItemBindingSource.OfType<POSGridItem>().FirstOrDefault(x => x.ProductId == product.Id);

                pOSGridItemBindingSource.Add(new POSGridItem
                {
                    IsTaxed = product.IsTaxed,
                    PriceAmount = product.CurrentPrice.Amount,
                    PriceId = product.CurrentPrice.Id,
                    ProductBarcode = product.Barcode,
                    ProductId = product.Id,
                    ProductName = product.Name,
                    Quantity = Convert.ToDouble(quantityTextEdit.Text) + existingItem.Quantity
                });
                pOSGridItemBindingSource.Remove(existingItem);
            }
            else 
            {
                pOSGridItemBindingSource.Add(new POSGridItem
                {
                    IsTaxed = product.IsTaxed,
                    PriceAmount = product.CurrentPrice.Amount,
                    PriceId = product.CurrentPrice.Id,
                    ProductBarcode = product.Barcode,
                    ProductId = product.Id,
                    ProductName = product.Name,
                    Quantity = Convert.ToDouble(quantityTextEdit.Text)
                });
            }

            UpdateTotalPrice();
            ResetProduct();

        }
        public void ResetProduct()
        {
            quantityTextEdit.Text = "1";

            barcodeTextEdit.ResetText();

            barcodeTextEdit.Focus();
            UpdateTotalPrice();
        }
        public void ChangeCustomer(Customer _customer)
        {
            if (_customer != null&& !string.IsNullOrEmpty(_customer.Code))
            {
                customer = _customer;
                customerTextEdit.Text = customer.CodeAndName;
            }
            else
            {
                customer = null;
                customerTextEdit.Text = "ไม่ระบุ";
            }

            barcodeTextEdit.Focus();
        }
        public void ChangePaymentType(PaymentType _paymentType)
        {
            paymentType = _paymentType;
            this.paymentTypeTextEdit.Text = paymentType.Name;
            if (paymentType.IsCredit)
                this.paymentTypeTextEdit.Text += ", เงินเชื่อ";
            if (this.paymentType.IsCaptitalPrice)
                this.paymentTypeTextEdit.Text += ", ราคาทุน";
        }
        public void ResetForm()
        {
            customer = null;
            customerTextEdit.Text = "ไม่ระบุ";

            ChangePaymentType(invoiceRepository.DefaultPaymentType());
            ChangeCustomer(null);

            pOSGridItemBindingSource.Clear();

            ResetProduct();
        }
        private void POSForm_Load(object sender, EventArgs e)
        {
            
        }
        private void POSForm_Shown(object sender, EventArgs e)
        {

            this.Text = "| ผู้ใช้ - " + employee.Name + " | ";
            int all = customerRepository.AllCustomers().Count();
            int count = 0;
            foreach (var customer in customerRepository.AllCustomers())
            {
                allCustomers.Add(customer);
                this.Text = "| ผู้ใช้ - " + employee.Name + " | ข้อมูลลูกค้า - " + (((float)count++ / (float)all) * 100).ToString("N2") + "% |";
            }
            all = productRepository.AllProducts().Count();
            count = 0;
            foreach (var product in productRepository.AllProducts())
            {
                allProducts.Add(product);
                this.Text = "| ผู้ใช้ - " + employee.Name + " | ข้อมูลลูกค้า - 100% | ข้อมูลสินค้า - " + (((float)count++ / (float)all) * 100).ToString("N2") + "% |";
            }
            this.Text = "| ผู้ใช้ - " + employee.Name + " | ข้อมูลลูกค้า - 100% | ข้อมูลสินค้า - 100% |";
        }
        
        private void barcodeTextEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(barcodeTextEdit.Text))
                {
                    try
                    {
                        AddProduct(allProducts.FirstOrDefault(x => x.Barcode == barcodeTextEdit.Text));
                    }
                    catch
                    {
                        MessageBox.Show("ไม่พบสินค้า");
                        barcodeTextEdit.ResetText();
                    }
                }
                else
                {
                    InvoiceSummaryForm invoiceSummaryForm = new InvoiceSummaryForm(this);
                    invoiceSummaryForm.Show();
                }

            }
            if (e.KeyCode == Keys.F1)
            {
                SelectProductForm selectProductForm = new SelectProductForm(this, allProducts);
                selectProductForm.Show();
            }
            if (e.KeyCode == Keys.F2)
            {
                barcodeTextEdit.Enabled = false;
                quantityTextEdit.Properties.ReadOnly = false;
                quantityTextEdit.Text = "1";
                quantityTextEdit.Focus();
            }
            if (e.KeyCode == Keys.F3)
            {
                SelectCustomerForm selectCustomerForm = new SelectCustomerForm(this,allCustomers);
                selectCustomerForm.Show();
            }
            if (e.KeyCode == Keys.F4)
            {
                SelectPaymentTypeForm selectPaymentTypeForm = new SelectPaymentTypeForm(this);
                selectPaymentTypeForm.Show();
            }

            if (e.KeyCode == Keys.F5)
            {
                RemoveProduct();
            }
            if (e.KeyCode == Keys.F6)
            {
                POSChangePriceForm form = new POSChangePriceForm(this);
                form.Show();

            }
        }
        private void quantityTextEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                quantityTextEdit.Properties.ReadOnly = true;
                barcodeTextEdit.Enabled = true;
                barcodeTextEdit.Focus();
            }
        }
        private void pOSGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                this.selectedItem = (POSGridItem)pOSGridView.GetRow(pOSGridView.GetSelectedRows()[0]);
                selectedProductTextEdit.Text = selectedItem.ProductName;
            }
            catch 
            {
                RemoveProduct();
                selectedProductTextEdit.ResetText();
            }
        }
        public void RemoveProduct()
        {
            try
            {
                pOSGridItemBindingSource.Remove(selectedItem);
            }
            catch { }
        }
        private void selectedProductTextEdit_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(selectedProductTextEdit.Text))
            {
                removeProductButton.Enabled = false;

            }
            else
            {
                removeProductButton.Enabled = true;
            }
        }
    }
}